import { NzMessageService } from 'ng-zorro-antd/message';
import { Component, Input, OnInit, Output, OnChanges, SimpleChanges, EventEmitter, ElementRef, ChangeDetectorRef, TemplateRef, ViewChild } from '@angular/core';
import { NzResizeEvent } from 'ng-zorro-antd/resizable';
//import { ConfigService } from '@/services/config.service';
// import { ConfigService } from '@src/app/services/config.service';

@Component({
  selector: 'app-table',
  templateUrl: './table.component.html',
  styleUrls: ['./table.component.less']
})
export class TableComponent implements OnInit, OnChanges {
  @Input() isColFilter: boolean=true;
  @Input()
  set pageIndex(val: number) {
    this.ppageIndex = val;
  }
  @Input()
  set pageSize(val: number) {
    this.ppageSize = val;
  }
  @Input() total: number=0;
  @Input() listData: any=[];
  @Input() 
  set theadData(val: any[]) {
    this.tHeadData = val || [];
    this.checkOptionsOne = this.tHeadData.map((item: any) => {
      return {
        label: item.label.replace(/(<([^>]+)>)/ig,""),
        value: item.prop,
        checked: true
      };
    });
    this.copyHeads = this.tHeadData;
    //this.copyListOfData = val && cloneDeep(val) || [];
    //this.refreshCheckedStatus();//数据改变之后重置全选按钮状态
  }
  @Input() //多级表头
  set multiTheadData(val: any[]){
    this.tHeadData = val || [];
  };
  @Input() set leafNodeColumn(val: any[]){
    this.leafNodeColumn1=val || [];
    this.nzWidthConfig=this.leafNodeColumn1.map((ele:any)=>ele.nzWidth);
  };
  @Input() isShowPagination: boolean=true;
  @Input() isShowQuickJumper: boolean=true;
  @Input() isHideOnSinglePage: boolean=false;
  @Input() loadTable: boolean=false;
  @Input() isHasAction: any=[];
  @Input() isCheckTable: boolean=false;
  @Input() nzScroll: any;
  @Input() tplSwitch: boolean=false;
  @Input() footerTpl: TemplateRef<void> | undefined;
  @Input() multiLevelHead: boolean=false;
  @Output() cellClick = new EventEmitter();
  @Output() editFun = new EventEmitter();
  @Output() deleteFun = new EventEmitter();
  @Output() choiceData = new EventEmitter();
  @Output() reloadTable = new EventEmitter();
  @Output() openEnclosure = new EventEmitter();
  @Output() afterStopEdit = new EventEmitter();
  @Output() beforeStartEdit = new EventEmitter();
  @Output() customData = new EventEmitter();
  // 返回选中项
  @Output() getCheckIdFun = new EventEmitter<any>();
  editId: string | null=null;
  editProp: string ='';
  currChoice:any;
  selectedIndex: number | undefined;
  tableChecked:boolean = false;//表格选中状态
  indeterminate:boolean = false;//表格checkbox indeterminate 状态
  indeterminateFilter:boolean=false;//列筛选checkbox indeterminate 状态
  setOfCheckedId = new Array<any>();//设置选中id
  filterAllChecked:boolean=true;//列筛选全选选中状态
  checkOptionsOne:any=[];//列筛选选中的数组
  copyHeads: any = [];
  tHeadData:any=[];
  config:any={};
  ppageIndex=1;
  ppageSize=10;
  resizing:boolean=false;
  leafNodeColumn1:any=[];
  nzWidthConfig: any=[];
  listOfCurrentPageData: any[] = [];
  constructor(
    private msgSvr:NzMessageService,
    //private configSvr:ConfigService,
    private eleRef :ElementRef,
    private cd: ChangeDetectorRef
  ) { }

  ngOnInit(): void {
    
  }

  //处理多层属性
  getDeepObj(data: any, d: string, split = '.'){
    let dArr = d.split(split);
    let r = data;
    for(let i = 0; i < dArr.length; i++){
        r = r[dArr[i]]
        if(!r){
            return r
        }
    }
    return r
  }

  ngOnChanges(changes:SimpleChanges) {
    if(changes.listData?.currentValue?.length){
      this.rowClick(changes.listData.currentValue[0],0);
    }else if(changes.listData?.currentValue?.length===0){
      this.rowClick(null);
    }
  }

  tableDataChange(listOfCurrentPageData: any[]){
    this.listOfCurrentPageData = listOfCurrentPageData;
    if(listOfCurrentPageData.length!=0){
      this.refreshCheckedStatus();
    }
  }

  nzQueryParams($event: any){
    if(this.resizing){
      return
    }
    this.reloadTable.emit($event)
  }

  getList(){
    
  }

  jumpTo(data: any,prop?: any){
    var params={data,prop}
    this.cellClick.emit(params);
  }

  //工程文件审核记录操作列
  op_a(op: any, data: any){
    let params={op, data}
    this.cellClick.emit(params);
  }
  //表格行选择
  rowClick(data: any,i?: number | undefined){
    if(data){
      this.selectedIndex=i;
      this.currChoice=data;
      this.choiceData.emit(data);
    }else{
      this.choiceData.emit(null);
    }
  }
  //表格更新选中
  updateCheckedSet(data: any, checked: boolean): void {
    if (checked) {
      //this.setOfCheckedId.add(data);
      this.setOfCheckedId=this.add(this.setOfCheckedId,data);
    } else {
      //this.setOfCheckedId.delete(data);
      this.setOfCheckedId=this.delete(this.setOfCheckedId,data);
    }
  }
  //表格项选中
  onItemChecked(data: any, checked: boolean): void {
    this.updateCheckedSet(data, checked);
    this.refreshCheckedStatus();
     this.getCheckIdFun.emit([...this.setOfCheckedId]);
  }
  //表格全选
  onAllChecked(value: boolean): void {
    if(this.listOfCurrentPageData.length!==0){
      this.listOfCurrentPageData.forEach(item => this.updateCheckedSet(item, value));
    }else{
      this.listData.forEach((item: any) => this.updateCheckedSet(item, value));
    }
    this.refreshCheckedStatus();
     this.getCheckIdFun.emit([...this.setOfCheckedId]);
  }
  //刷新表格选中状态
  refreshCheckedStatus(): void {
    if(this.listOfCurrentPageData.length!==0){
      this.tableChecked = this.listOfCurrentPageData.every(item => this.has([...this.setOfCheckedId],item));
      this.indeterminate = this.listOfCurrentPageData.some(item => this.has([...this.setOfCheckedId],item)) && !this.tableChecked;
    }else{
      if(this.listData.length==0){
        this.tableChecked=false;
        this.indeterminate=false;
        return
      }
      this.tableChecked = this.listData.every((item: any) => this.has([...this.setOfCheckedId],item));
      this.indeterminate = this.listData.some((item: any) => this.has([...this.setOfCheckedId],item)) && !this.tableChecked;
    }
    
    //this.cd.detectChanges();
  }

  has(arr: any[],item: any){
    let flag=false;
    arr.forEach(element => {
      if(element.TempGuid){
        if(element?.TempGuid===item?.TempGuid) flag=true;
      }else{
        if(element.Guid===item.Guid) flag=true;
      }
    });
    return flag;
  }

  add(arr: any[],item: any){
    var f=this.has(arr,item)
    if(!f) arr.push(item);
    return arr;
  }

  delete(arr: any[],item: any){
    for(var i=0;i<arr.length;i++) {
      if(arr[i].TempGuid){
        if(arr[i].TempGuid===item?.TempGuid) {
          arr.splice(i,1);
          i--;
        }
      }else{
        if(arr[i].Guid===item.Guid) {
          arr.splice(i,1);
          i--;
        }
      }
    }
    return arr;
  }


  //列筛选全选处理
  updateAllChecked(): void {
    this.indeterminateFilter = false;
    if (this.filterAllChecked) {
      this.checkOptionsOne = this.checkOptionsOne.map((item:any) => ({
        ...item,
        checked: true
      }));
    } else {
      this.checkOptionsOne = this.checkOptionsOne.map((item:any) => ({
        ...item,
        checked: false
      }));
    }
    this.tHeadData = this.filterHeads(this.checkOptionsOne, this.copyHeads).filter((item:any) => {
      return item.isshow == true;
    });
  }
  //列筛选单选处理
  updateSingleChecked(): void {
    if (this.checkOptionsOne.every((item:any) => !item.checked)) {
      this.filterAllChecked = false;
      this.indeterminateFilter = false;
    } else if (this.checkOptionsOne.every((item:any) => item.checked)) {
      this.filterAllChecked = true;
      this.indeterminateFilter = false;
    } else {
      this.indeterminateFilter = true;
    }
    this.tHeadData = this.filterHeads(this.checkOptionsOne, this.copyHeads).filter((item:any) => {
      return item.isshow == true;
    });
  }

  filterHeads(checkdata: any[], headData: any[]) {
    checkdata.forEach(itemc => {
      headData.forEach(itemh => {
        if (itemc.value == itemh.prop) {
          itemh.isshow = itemc.checked;
        }
      });
    });
    return headData;
  }

  editAction(data: any){
    this.editFun.emit(data);
  }

  deleteAction(data: any){
    this.deleteFun.emit(data);
  }

  cancel(){

  }

  startEdit(e: any,data: any,prop: string){
    if(data.Guid){
      this.editId = data.Guid;
      this.editProp = prop;
    }else{
      this.editId = data.TempGuid;
      this.editProp = prop;
    }
    this.beforeStartEdit.emit({data,prop});
    //this.eleRef.nativeElement.querySelector('')
  }

  hidden(type: number,data: any,item: any){
    if(data.Guid){
      if(type==1){
        if(data.Guid===this.editId&&item.prop===this.editProp){
          return true
        }
        if(data.Guid===this.editId&&item.prop!==this.editProp){
          return false
        }
        if(data.Guid!==this.editId&&item.prop===this.editProp){
          return false
        }
        if(data.Guid!==this.editId&&item.prop!==this.editProp){
          return false
        }
      }else{
        if(data.Guid===this.editId&&item.prop===this.editProp){
          return false
        }
        if(data.Guid===this.editId&&item.prop!==this.editProp){
          return true
        }
        if(data.Guid!==this.editId&&item.prop===this.editProp){
          return true
        }
        if(data.Guid!==this.editId&&item.prop!==this.editProp){
          return true
        }
      }
    }else{
      if(type==1){
        if(data.TempGuid===this.editId&&item.prop===this.editProp){
          return true
        }
        if(data.TempGuid===this.editId&&item.prop!==this.editProp){
          return false
        }
        if(data.TempGuid!==this.editId&&item.prop===this.editProp){
          return false
        }
        if(data.TempGuid!==this.editId&&item.prop!==this.editProp){
          return false
        }
      }else{
        if(data.TempGuid===this.editId&&item.prop===this.editProp){
          return false
        }
        if(data.TempGuid===this.editId&&item.prop!==this.editProp){
          return true
        }
        if(data.TempGuid!==this.editId&&item.prop===this.editProp){
          return true
        }
        if(data.TempGuid!==this.editId&&item.prop!==this.editProp){
          return true
        }
      }
    }
    
    
  }

  stopEdit(id: any,prop: any){
    this.editId = null;
    this.editProp = '';
    let obj:any={};
    obj.prop=prop
    this.listData.forEach((ele:any)=>{
      if(ele.Guid==id){
        obj.data=ele;
        this.afterStopEdit.emit(obj);
      }
    });
  }

  IsNum(type?: string){
    if(type==='number'||type==='money'||type==='KZJRatio'||type==='numberTree'||type==='numberThree'){
      return true;
    }else{
      return false;
    }
  }

  sizeOptions(){
    return [10,20,30,40,50,100]
  }


  //打开附件
  openEnclo(data: any){
    this.openEnclosure.emit(data);
  }


  onResize({ width }: NzResizeEvent, col: string): void {
    setTimeout(()=>{
      this.resizing=false;
    },100)
    this.tHeadData = this.tHeadData.map((e:any) => (e.prop === col ? { ...e, nzWidth: `${width}px` } : e));
  }

  onResizeStart({ width }: NzResizeEvent, col: string){
    this.resizing=true;
  }

  // onMultiLevelHeadTableResize({ width }: NzResizeEvent, prop: string): void{
  //   this.setWidth(prop, width, this.leafNodeColumn1);
  //   this.ConfigWidth(this.cols);
  // }

  setWidth(key: any, width: string, arr: any[]) {
    arr.forEach((item) => {
      item.forEach((ele: any) => {
        if (ele.width) {
          if (ele.field == key) {
            ele.width = width + 'px';
          }
        }
      });
    });
  }

  //宽度配置
  // ConfigWidth(cols?): any {
  //   let arr=[];
  //   if (!cols) {
  //     arr=this.cols;
  //   }else{
  //     arr = cols;
  //   }
  //   let widths = [];
  //   let temp = [];
  //   arr.forEach((element) => {
  //     element.forEach((item) => {
  //       if ((item.isLeaf && item.rowspan==1) || item.label==='序号'|| item.label==='项目名称' || item.label==='主要工程量') {
  //         item.width = item.width ? item.width : '80px';
  //         widths.push(item.width);
  //       }else if(item.isLeaf && item.rowspan!=1){
  //         item.width = item.width ? item.width : '80px';
  //         temp.push(item.width);
  //       }
  //     });
  //   });
  //   let newArr=widths.concat(temp);
  //   return newArr;
  // }
}
